using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using IAS.MacroRenderings.Interfaces;
using System.Web;
using FileHelpers;
namespace IAS.MacroRenderings.Data
{
    /// <summary>
    /// used to provide via csv file (separated by | ) the drop down data
    /// TODO add some kind of filewatcher on the file and some caching so cache it and if the filewatcher change / delete event fires up then
    /// clear the cache
    /// </summary>
    public class DataCSV : DataBase, IDropDownListDataProvider
    {

        private const string csvFolder = "/data/MacroRenderings/csv/";
        private const string extension = ".csv";
        #region IDropDownListDataProvider Members

        public Dictionary<string, string> GetData()
        {
            //making assumption that the csv file name is same as class name and that it contains data
            //as | separated key value
            string csvFile = HttpContext.Current.Server.MapPath(csvFolder + className + extension);
            Dictionary<string, string> dt = new Dictionary<string, string>();

            try
            {
                FileHelperEngine engine = new FileHelperEngine(typeof(CSVRecord));
                CSVRecord[] res = engine.ReadFile(csvFile) as CSVRecord[];

                foreach (CSVRecord c in res)
                {
                    dt.Add(c.Key, c.Value);
                }
            }
            catch (Exception ex) {
                this.LogErrorToUmbraco(ex.Message.ToString() + " processing csv file " + csvFile);
            }

            return dt;
        }

        public string ClassName
        {
            set { this.className = value; }
        }

        #endregion
    }


    /// <summary>
    /// this class is used by filehelpers to do the csv read for a pipe separated file
    /// not using , just in case you want that in your data
    /// </summary>
    [DelimitedRecord("|")]
    public sealed class CSVRecord
    {

        [FieldOptional(), FieldQuoted(QuoteMode.OptionalForBoth)]
        [FieldNullValue(typeof(String), "")]
        public String Key;

        [FieldOptional(), FieldQuoted(QuoteMode.OptionalForBoth)]
        [FieldNullValue(typeof(String), "")]
        public String Value;

    }

}
